package mobileann.mafamily.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import mobileann.mafamily.act.main.FS;
import mobileann.mafamily.act.setup.HelperActivity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import com.mofind.android.base.L;

/**
 * 功能: 
 * @author Adrian
 */
public class ImageTask extends AsyncTask<String, Integer, Bitmap> {

	public interface ImageTaskCallBack {
		public Bitmap getBitmap(Bitmap bitmap);
	}

	private ImageTaskCallBack listener;

	private boolean isRead = true;

	public ImageTask(boolean isRead) {
		this.isRead = isRead;
		this.listener = null;
	}

	public ImageTask(ImageTaskCallBack listener) {
		this.listener = listener;
		isRead = true;
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		if (isRead) { // 正常获取图片
			Bitmap loadImageFromLocal = loadImageFromLocal(params[0]);
			if (loadImageFromLocal != null) {
				return loadImageFromLocal;
			}
			Bitmap loadImage = loadImage(params[0]);
			if (loadImage != null) {
				saveImgToSD(params[0], loadImage);
				return loadImage;
			}
		} else { // 下载图片如果本地不存在
			downloadBitmap(params[0]);
		}
		return null;			
	}

	public void downloadBitmap(String url){
		//TODO Log.i(HelperActivity.ADRIAN, "downloadBitmap begin");
		if(!isBitmapExists(url)) {
			Bitmap loadImage = loadImage(url);
			if (loadImage != null) {
				//TODO Log.i(HelperActivity.ADRIAN, "downloadBitmap into SD card");
				saveImgToSD(url, loadImage);
			}
		}
		//TODO Log.i(HelperActivity.ADRIAN, "downloadBitmap end");
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		super.onPostExecute(result);
		if (listener != null && result != null) {
			listener.getBitmap(result);
		}
	}

	/** 得到图片的路径地址 */
	public String getBitmapImagePath(String url){
		String iamgeName = MD5.getMD5FromUrl(url);
		StringBuilder sbImgPath = new StringBuilder(128);
		String userLogoFilesPath = UserLogoFilesPath();
		if(userLogoFilesPath == null){
			return null;
		}
		sbImgPath.append(userLogoFilesPath);
		sbImgPath.append(File.separator);
		sbImgPath.append(iamgeName);
		//TODO Log.i(HelperActivity.ADRIAN, sbImgPath.toString());
		return sbImgPath.toString();
	}

	/** 从本地得到图片 */
	public Bitmap loadImageFromLocal(String url){
		if(!isBitmapExists(url)) return null;
		try {
			//TODO　Log.i(HelperActivity.ADRIAN, "loadimageFromLocal");
			String bitmapImagePath = getBitmapImagePath(url);
			if (bitmapImagePath == null) {
				return null;
			}
			File img = new File(bitmapImagePath);
			FileInputStream fis = new FileInputStream(img);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 判断本地图片是否存在 */
	public boolean isBitmapExists(String url){
		//TODO Log.i(HelperActivity.ADRIAN, "isBitmapExists(String)");
		String bitmapImagePath = getBitmapImagePath(url);
		if (bitmapImagePath == null) {
			return false;
		}
		File img = new File(bitmapImagePath);
		//TODO Log.i(HelperActivity.ADRIAN, "img.exists---"+img.exists());
		return img.exists();
	}

	/** 从网络下载图片 */
	public Bitmap loadImage(String url) {  
		//TODO  Log.i(HelperActivity.ADRIAN, "loadImage from network");
		Bitmap bitmap = null;  
		HttpClient client = new DefaultHttpClient();  
		HttpResponse response = null;  
		InputStream inputStream = null;  
		try {  
			response = client.execute(new HttpGet(url));  
			HttpEntity entity = response.getEntity();  
			inputStream = entity.getContent(); 
			bitmap = BitmapFactory.decodeStream(inputStream);  
		} catch (ClientProtocolException e) {  
			e.printStackTrace();  
		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		return bitmap;  
	}  

	/**
	 * 主要功能：
	 * <br>1.创建图片存储的路径,相当于存储icon图像的根路径
	 * @return
	 * @annotation ADRIAN.2015.7.17.10.42
	 */
	public  String UserLogoFilesPath() {
		String path = FS.getInstance().getFilesDir().getAbsolutePath()
				+ File.separator + "MABaby" + File.separator
				+ "MAFamilyHelpImage";
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			path = (Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
					+ "MABaby" + "/MAFamilyHelpImage");
		}
		File dir = new File(path);
		if (!dir.exists()) {
			if(!dir.mkdir()){
				//TODO Log.i(HelperActivity.ADRIAN, "dir.mkdir is null!");
				return null;
			}
			//TODO Log.i(HelperActivity.ADRIAN, "dir.mkdir()");
		}
		//TODO Log.i(HelperActivity.ADRIAN, "dir.exists--->"+dir.exists());
		dir = null;
		//TODO Log.i(HelperActivity.ADRIAN, "dir.exists---path--->"+path);
		return path;
	}

	/**
	 * 将图片保存到SD卡
	 * @param iconName
	 * @param bitmap
	 */
	public synchronized void saveImgToSD(String url,Bitmap bitmap) {
		if (bitmap == null) return ; 
		if (url == null) return ; // 只要有一种情况为空,都返回,避免空指针异常.
		//TODO Log.i(HelperActivity.ADRIAN, "saveImgtoSD");
		String bitmapImagePath = getBitmapImagePath(url);
		if (bitmapImagePath == null) {
			return ;
		}
		File photoFile = new File(bitmapImagePath); //在指定路径下创建文件
		if (photoFile.exists()) {
			return;
		}
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(photoFile);
			if (bitmap != null) {
				if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)) {
					fileOutputStream.flush();
				}
			}
		} catch (FileNotFoundException e) {
			if (photoFile!=null && photoFile.exists())
				photoFile.delete();
			e.printStackTrace();
		} catch (IOException e) {
			if (photoFile!=null && photoFile.exists()) 
				photoFile.delete();
			e.printStackTrace();
		} finally {
			try {
				fileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
